#include <slothttpd/server.hpp>
#include <slothttpd/config/configuration.hpp>
#include <slothttpd/logger.hpp>
#include <slothttpd/stage/proxy_fcgi.hpp>
#include <slothttpd/stage/receive_request.hpp>
#include <slothttpd/stage/send_file.hpp>
#include <slothttpd/stage/send_headers.hpp>

#include <cstddef>
#include <cstring>
#include <cerrno>

#include <exception>
#include <iostream>
#include <string>

#include <sys/resource.h>
#include <unistd.h>

#include <boost/exception/diagnostic_information.hpp>

int main(int argc, char *argv[])
{
    using namespace slothttpd;
    
    std::cerr << sizeof(connection) << '\n';
    std::cerr << sizeof(stage::receive_request) << '\n';
    std::cerr << sizeof(stage::send_headers) << '\n';
    std::cerr << sizeof(stage::send_file) << '\n';
    std::cerr << sizeof(stage::proxy_fcgi) << '\n';
    
    config::configuration::instance = config::configuration::from_file("config.json");
    server::instance.reset(new server(config::configuration::instance));
    
    struct rlimit fd_limit;
    
    fd_limit.rlim_cur = 16 * 1024;
    fd_limit.rlim_max = 16 * 1024;
    
    if (setrlimit(RLIMIT_NOFILE, &fd_limit) != 0) {
        logger() << "setrlimit(RLIMIT_NOFILE, &) failed: " << strerror(errno) << std::endl;
    }
    
    slothttpd::server::instance->run();
    /*
    try {
        slothttpd::server::instance->run();
    } catch (const std::exception &ex) {
        logger() << "process pid " << getpid() << " exits abnormally: " << ex.what() << std::endl;
    }
    */
}

